package com.thirdgroup.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
 * @BelongsProject: gxa-thrid-team
 * @BelongsPackage: com.thirdgroup.utils
 * @Author: ZYS
 * @CreateTime: 2024-05-07  19:27
 * @Description: TODO
 */
public class DruidLocalUtil {
    private static final DataSource dataSource;

    static {
        Properties properties = new Properties();
        try {
            properties.load(DruidLocalUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
//            properties.load(DruidLocalUtil.class.getClassLoader().getResourceAsStream("src/main/resources/druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //关闭结果集
    public static void closeResultSet(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //关闭预处理对象
    public static void closeStatement(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //关闭数据库连接
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //一次性关闭上面三个
    public static void closeResource(ResultSet resultSet, Statement statement, Connection connection) {
        closeResultSet(resultSet);
        closeStatement(statement);
        closeConnection(connection);
    }
}
